package aishua.com.mytestapplist;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.net.wifi.p2p.WifiP2pConfig;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import aishua.com.mytestapplist.apdu.MyApduAdapter;
import aishua.com.mytestapplist.bean.ItemBean;
import aishua.com.mytestapplist.datastructure.MyLink;
import aishua.com.mytestapplist.mimaxiang.DragAdapter;
import aishua.com.mytestapplist.mimaxiang.DragGridView;
import aishua.com.mytestapplist.mimaxiang.UserInfo;
import aishua.com.mytestapplist.msgbean.ReqDeviecinfoSynBean;
import aishua.com.mytestapplist.msgbean.ReqUserLoginBean;
import aishua.com.mytestapplist.utils.LogUtils;
import chinatelecom.mwallet.open.service.INFCOpenAbility;
import chinatelecom.mwallet.open.service.IProgressCallback;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.http2.Header;


/**
 * Created by aishua on 2017/5/4.
 */

public class TestActivity extends Activity {
    private static final String TAG = "TestActivity-";
    private DragGridView mDragGridView;
    private List<UserInfo> detailList = new ArrayList();
    private String[] strs = {"支付宝", "微信", "翼支付", "钱包", "QQ", "王者荣耀", "北京一卡通", "威海电信市民卡", "滴滴"};
    private Context mContext;
    private Button btn_singleinstance;
    private Button btn_clickinit;
    private TextView tv_singleInstance;
    private ImageView img_glide;
    //    https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2210270529,1470505196&fm=11&gp=0.jpg 测试图片地址
    private String imageurl = "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2210270529,1470505196&fm=11&gp=0.jpg";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LogUtils.v(TAG + "----onCreat()");
        mContext = this;
//        mDragGridView = (DragGridView) findViewById(R.id.dragGridView);
//        writeSMS();
//        LogUtils.v(convert("~!@#%$%&*()-_+=-{}[]:;'<>?,./|qwertyuioplkjhgfdsazxcvbnm"));
//        LogUtils.v("Math.round(-11.49)---->"+Math.round(-11.49) );
        Integer b = new Integer(3);
        Integer c = 3;
//        LogUtils.v("Integer---->"+(b==c));
        //插件vitamio框架检查是否可用
//        if (!LibsChecker.checkVitamioLibs(this)) {
//            return;
//        }
        btn_singleinstance = (Button) findViewById(R.id.btn_singleInstance);
        tv_singleInstance = (TextView) findViewById(R.id.tv_singleInstance);
        btn_clickinit = (Button) findViewById(R.id.btn_clickinit);

        img_glide = (ImageView) findViewById(R.id.img_glide);
        tv_singleInstance.setText("Current Task id is" + getTaskId());
//        postAsynHttp();
        btn_singleinstance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(TestActivity.this,SecondActivity.class);
//                startActivity(intent);
//                Intent intent = new Intent(TestActivity.this,TestService.class);
//                startService(intent);
//                Glide.with(TestActivity.this).load(imageurl).into(img_glide);
//              LogUtils.v(TAG+" testSwitchcase()-->"+testSwitchcase(1));
//                postAsynHttp();
//                getDataAsync();

                test1();
            }
        });
//        帧动画 （frame动画）
//        img_glide.setBackgroundResource(R.drawable.frameanimaton);
//        AnimationDrawable animationDrawable = (AnimationDrawable) img_glide.getBackground();
//        animationDrawable.start();
        final Animation animation = AnimationUtils.loadAnimation(this, R.anim.alpha_anim);
        img_glide.startAnimation(animation);
        animation.setInterpolator(new AccelerateDecelerateInterpolator());

        testMylink();
        btn_clickinit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        try {

                            LogUtils.v(TAG + "Thread.name--->" + Thread.currentThread().getName());
                            abi.init("1234667", "aishua.com.mytestapplist");
                        } catch (RemoteException e) {

                            e.printStackTrace();
                        }
                    }
                }.start();

            }
        });
    }

    private void testMylink() {

    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtils.v(TAG + "----onStart()");
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.v(TAG + "----onResume()");

    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.v(TAG + "----onPause()");

    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.v(TAG + "----onStop()");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.v(TAG + "----onDestroy()");

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtils.v(TAG + "----onRestart()");

    }

    public void myDragGridV() {

        for (int i = 0; i < 9; i++) {
            UserInfo message = new UserInfo();
            String str = strs[i];
            message.setMsg(str);
            detailList.add(message);


        }
        for (int j = 9; j < 30; j++) {
            UserInfo message = new UserInfo();
            String str = "APP:" + j + "";
            message.setMsg(str);
            detailList.add(message);


        }

        mDragGridView.setAdapter(new DragAdapter(mContext, (ArrayList<UserInfo>) detailList));
    }

    public void writeSMS() {


        Uri uri = Uri.parse("content://sms/");
        //创建ContentValues
        ContentValues values = new ContentValues();
        values.put("address", "10086");
        values.put("body", "您已经欠费");
        values.put("date", System.currentTimeMillis());
        getContentResolver().insert(uri, values);
        getContentResolver().insert(uri, values);
        getContentResolver().insert(uri, values);
    }

    /**
     * 将字符串转成unicode
     *
     * @param str 待转字符串
     * @return unicode字符串
     */
    public String convert(String str) {
        str = (str == null ? "" : str);
        String tmp;
        StringBuffer sb = new StringBuffer(1000);
        char c;
        int i, j;
        sb.setLength(0);
        for (i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            sb.append("\\u");
            j = (c >>> 8); //取出高8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
            j = (c & 0xFF); //取出低8位
            tmp = Integer.toHexString(j);
            if (tmp.length() == 1)
                sb.append("0");
            sb.append(tmp);
        }
        return (new String(sb));

    }

    public int testSwitchcase(int i) {
        int j;
        switch (i) {

            case 1:
                j = 1;
                return j;
            case 2:
                break;
            case 3:
                break;
            default:
                break;
        }
        return 10;
    }

    String header;

    private void postAsynHttp() {

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {

                        Response originalResponse = chain.proceed(chain.request());
                        header = originalResponse.header("Authorization");
                        return originalResponse;
                    }
                })
                .build();
        ReqUserLoginBean reqUserLoginBean = new ReqUserLoginBean();
        reqUserLoginBean.setReq_sequenceid("2018040412360001");
        reqUserLoginBean.setOptype("1");
        reqUserLoginBean.setAccount("user");
        reqUserLoginBean.setPw("user");
        reqUserLoginBean.setApp_ver("1.0.0");
        String parm = new Gson().toJson(reqUserLoginBean);
        //MediaType  设置Content-Type 标头中包含的媒体类型值
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , parm);

        Request request = new Request.Builder()
                .url("http://61.149.254.38:10123/appLogin")//请求的url
                .post(requestBody)
                .build();


        //创建/Call
        Call call = okHttpClient.newCall(request);
//        String header =call.request().header("Authorization");
//        LogUtils.v(TAG +"header"+header);

        //加入队列 异步操作
        call.enqueue(new Callback() {
            //请求错误回调方法
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("连接失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());

            }
        });
    }

    public void test() {

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        ReqDeviecinfoSynBean reqUserLoginBean = new ReqDeviecinfoSynBean();
        reqUserLoginBean.setReq_sequenceid("2018040412360001");
        reqUserLoginBean.setOptype("1");
        reqUserLoginBean.setDeviceinfolist(null);
        reqUserLoginBean.setIot_target_num("0");
        String parm = new Gson().toJson(reqUserLoginBean);
        LogUtils.v(TAG + "testparm:" + parm);
        //MediaType  设置Content-Type 标头中包含的媒体类型值
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , parm);
        LogUtils.v(TAG + "HEADER--->" + header);
        Request request = new Request.Builder()
                .url("http://61.149.254.38:10123/enterpriseSync")//请求的url
                .post(requestBody)
                .addHeader("Authorization", header)
                .build();


        //创建/Call
        Call call = okHttpClient.newCall(request);
//        String header =call.request().header("Authorization");
//        LogUtils.v(TAG +"header"+header);

        //加入队列 异步操作
        call.enqueue(new Callback() {
            //请求错误回调方法
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("连接失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                System.out.println(response.body().string());

            }
        });
    }

    public void test1() {

        Intent i = new Intent();
        i.setAction("chinatelecom.mwallet.open.service.SeOprService");
        i.setPackage("aishua.com.mytestapplist");
        i.setPackage("chinatelecom.mwallet.open");        //startService(i);i
        bindService(i, conn, Activity.BIND_AUTO_CREATE);
    }

    private void getDataAsync() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://tsm.bjaishua.com/getLoginCode")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {//回调的方法执行在子线程。测试衍合操作，在master分支上
                    Log.d("kwwl", "获取数据成功了");
                    Log.d("kwwl", "response.code()==" + response.code());
                    Log.d("kwwl", "response.body().string()==" + response.body().string());
                }
            }
        });
    }

    private NfcAdapter mNfcAdapter;

    public void tesetgit() {

        LogUtils.v(TAG + "测试git分之，输出一号develop分之");
        LogUtils.v(TAG + "测试git分之，提交hotfix分之");
        mNfcAdapter = mNfcAdapter.getDefaultAdapter(this);
    }

    INFCOpenAbility abi;
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            abi = INFCOpenAbility.Stub.asInterface(service);
            LogUtils.v("bind service success");
            Toast.makeText(getApplicationContext(), "绑定服务成功", 400).show();

        }
    };
    IProgressCallback call = new IProgressCallback.Stub() {

        @Override
        public void progress(String aid, String des, int progress)
                throws RemoteException {
            System.out.println("callback progress=" + progress + "aid=" + aid
                    + "des=" + des);
            LogUtils.v("callback progress=" + progress + "  aid=" + aid
                    + "  des=" + des);
//			Toast.makeText(getApplicationContext(), des, 200).show();
        }

        @Override
        public void notify(String resCode, String resDes)
                throws RemoteException {
            LogUtils.v("callback notify " + "resCode= " + resCode + " resDes= " + resDes);
        }
    };

}
